﻿using System;
using MediatR;
using Casamiel.Domain.Response;
using Microsoft.Extensions.DependencyInjection;
using Casamiel.Domain.Response.Account;
using System.Net.Http;
using Microsoft.Extensions.Options;
using Casamiel.Common;
using System.Threading.Tasks;
using System.Threading;
using Newtonsoft.Json;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class GetMemberInfoCommandHandler : BaseCommandHandler, IRequestHandler<GetMemberInfoCommand, BaseResult<MemberInfoResponse>>
	{
		private readonly IServiceScopeFactory _scopeFactory;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="serviceScopeFactory"></param>
		/// <param name="netICService"></param>
		/// <param name="httpClientFactory"></param>
		/// <param name="settings"></param>
		public GetMemberInfoCommandHandler(IServiceScopeFactory serviceScopeFactory, INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)
		{

			_scopeFactory = serviceScopeFactory;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<BaseResult<MemberInfoResponse>> Handle(GetMemberInfoCommand request, CancellationToken cancellationToken)
		{
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}

			using var scope = _scopeFactory.CreateScope();
			var _MemberService = scope.ServiceProvider.GetRequiredService<IMemberService>();
			var _cardService = scope.ServiceProvider.GetRequiredService<IMemberCardService>();
			var url = "v3/MemberCard/GetCardMember";
			var result = await PostThirdApiAsync<MemberInfoResponse>(url, JsonConvert.SerializeObject(request)).ConfigureAwait(false);
			var member = await _MemberService.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);

			if (result.Code==0 && result.Content == null) {
				var cardinfo = await _cardService.FindAsync<ICasaMielSession>(request.Mobile, false).ConfigureAwait(false);
				 MemberInfoResponse entity = new MemberInfoResponse {
				 Mobile=request.Mobile,
				 Birthday=member.Birthday,
				 RealName=member.Nick,
				 CardNo= cardinfo?.CardNO,
				 CardType=cardinfo?.CardType=="1"?1:2,
				 RegisterTime=member.CreateDate.Value,
				 InvitationCode=member.InvitationCode,
				 };
				return new BaseResult<MemberInfoResponse>(entity, 0, "");
			}
			if (result.Content != null) {

				result.Content.InvitationCode = member.InvitationCode;

			}
				//var data = new { Mobile = member.Mobile, Nick = member.Nick, Birthday = member.Birthday, Sex = member.Sex, TrueName = member.TrueName, Email = member.Email, member.InvitationCode };
				//var a = new { code = 0, data = data };
			return result;
		}
	}
}
